package com.zqh.forum.services.impl;

import com.zqh.forum.common.AppResult;
import com.zqh.forum.common.ResultCode;
import com.zqh.forum.dao.ArticleMapper;
import com.zqh.forum.exception.ApplicationException;
import com.zqh.forum.model.Article;
import com.zqh.forum.model.Board;
import com.zqh.forum.model.User;
import com.zqh.forum.services.IArticleService;
import com.zqh.forum.services.IBoardService;
import com.zqh.forum.services.IUserService;
import com.zqh.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.sql.SQLTransactionRollbackException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 写入的数据类
 */
@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    //用户和板块的操作
    //因为在这个板块里面我们进行数据的添加的时候，
    // 我们会影响到数据库中的其他两个表的更新，所以我们还需要注入其他两个services

    @Autowired
    private IUserService userService;

    @Autowired
    private IBoardService boardService;

    @Override
    public void create(Article article) {
        //非空校验
        if(article == null ||
                article.getUserId() == null ||
                article.getBoardId() == null ||
                StringUtil.isEmpty(article.getTitle()) ||
                StringUtil.isEmpty(article.getContent())){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //设置默认值
        article.setVisitCount(0); //访问数
        article.setReplyCount(0); //回复数
        article.setLikeCount(0);  //点赞数
        article.setDeleteState((byte)0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);
        //将数据写入数据库
        int row = articleMapper.insertSelective(article);
        if(row != 1){
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //插入正常
        //1.更新用户的发帖数量
        //查询用户的信息
        User user = userService.selectById(article.getUserId());
        if(user == null){
            //未找到指定的用户
            log.warn(ResultCode.FAILED_CREATE.toString() + ",发帖失败 user id =" + article.getUserId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //查询到用户，更新用户的发帖数量
        userService.addOneArticleCountById(user.getId());

        //2.获取板块的信息
        Board board = boardService.selectById(article.getBoardId());
        if(board == null){
            //未找到指定的用户
            log.warn(ResultCode.FAILED_CREATE.toString() + ",发帖失败 board id =" + article.getBoardId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //更新板块中的id数
        boardService.addOneArticleCountById(board.getId());
        //打印日志
        log.info(ResultCode.SUCCESS.toString() +
                "user id=" + article.getUserId() +
                "board id=" + article.getBoardId() +
                "article id=" + article.getId() + "发帖成功。");
    }

    @Override
    public List<Article> selectAll() {
         //调用Dao
        List<Article> articles = articleMapper.selectAll();

        return articles;
    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        //1.非空校验
        if(boardId == null || boardId <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.校验板块是否存在
        Board board = boardService.selectById(boardId);
        if(board == null){
            //为空
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        //3.调用DAO层
        List<Article> articles = articleMapper.selectAllByBoardId(boardId);
        //4.返回结果
        return articles;
    }

    @Override
    public Article selectDetailById(Long id) {
        //1.非空校验
        if(id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.根据帖子id查询帖子信息
        Article article = articleMapper.selectDetailById(id);
        if(article == null){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //3.帖子存在（更新操作），将帖子的访问量进行+1
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount() + 1);//访问数+1
        //保存数据到数据库
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1){
            //抛出异常
            log.warn(ResultCode.SUCCESS.toString());
            //打印日志
            throw new ApplicationException(AppResult.failed(ResultCode.SUCCESS));
        }
        //将之前查询的帖子里面的访问数量进行+1，因为上面呈现出来的还是没有进行增加操作的数量
        article.setVisitCount(article.getVisitCount() + 1);
        //4.返回帖子详情

        return article;
    }

    @Override
    public Article selectById(Long id) {
        //非空校验
        if(id == null || id <= 0 ){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用DAO
        Article article = articleMapper.selectByPrimaryKey(id);
        return article;
    }

    @Override
    public void modify(Long id, String title, String content) {
        //非空校验
        if(id == null ||
                id <= 0 ||
                !StringUtils.hasLength(title) ||
                !StringUtils.hasLength(content)){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //构建要更新的内容
        Article updateArticle = new Article();
        updateArticle.setId(id);//设置id
        updateArticle.setTitle(title);//设置标题
        updateArticle.setTitle(content);//设置内容
        updateArticle.setUpdateTime(new Date());//更新时间
        //调用DAO中的方法
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1){
            //打印日志
            log.warn(ResultCode.FAILED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void thumbsUpById(Long id) {
        //1.非空校验
        if(id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.根据帖子id查询帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        //3.判断帖子是否存在
        //帖子不存在或者已经删除
        if(article == null|| article.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //判断帖子或者用户禁言
        if(article.getState() == 1 ){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //4.构建更新的内容
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount() + 1);//点赞数+1
        updateArticle.setUpdateTime(new Date());
        //5.调用DAO层
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

    }

    @Override
    public void deleteById(Long id) {
        //1.非空校验
        if(id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.根据帖子id查询帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        //3.判断帖子是否存在
        //帖子不存在或者已经删除
        if(article == null|| article.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //4.构建更新的内容
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte) 1);
        updateArticle.setUpdateTime(new Date());
        //5.调用DAO层
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);

        if(row != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //6.更新用户的发帖数和板块的帖子数
        userService.subOneArticleCountById(article.getUserId());
        boardService.subOneArticleCountById(article.getBoardId());
        log.info("删除帖子成功， article id =" + article.getId() + "user id=" + article.getUserId() + "board id=" + article.getBoardId());

    }

    @Override
    public void addOneReplyCountById(Long id) {
        //1.非空校验
        if(id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取帖子记录+1
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article == null || article.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //禁言状态（封帖）
        if(article.getState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //更新操作
        //构造更新操作
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        //回复数量+1
        updateArticle.setReplyCount(article.getReplyCount() + 1);
        updateArticle.setUpdateTime(new Date());

        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        //非空校验
        if(userId == null || userId <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验用户是否存在
        User user = userService.selectById(userId);
        if(user == null){
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        List<Article> articles = articleMapper.selectByUserId(userId);
        return articles;
    }
}
